﻿using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Service;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Net.Http.Headers;

namespace AntUnion.FrameWork.Web.Common
{
    /// <summary>
    /// 图像工厂
    /// </summary>
    public class ImageFactory
    {
        private static Dictionary<string, string> imgFormatDic = new Dictionary<string, string> {
                {".jpg","image/jpeg"},
                {".jpeg","image/jpeg"},
                {".jpe","image/jpeg"},
                {".png","image/png"},
                {".bmp","image/bmp"}
        };

        public static Dictionary<string, string> GetImgFormat()
        {
            return imgFormatDic;
        }

        /// <summary>
        /// 自动创建缓存文件夹
        /// </summary>
        /// <param name="env">根目录环境</param>
        /// <returns>创建的文件夹路径</returns>
        public static string CreateFolder(IWebHostEnvironment env)
        {
            //根据时间生成路径名称
            string fileFolder = DateTimeUtil.Now.ToString("yyyyMM");
            string filePath = env.WebRootPath + $@"\UpLoad\{fileFolder}\";
            //创建文件夹
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            return filePath;
        }

        public static string CreateFileName(string oldName)
        {
            string extName = Path.GetExtension(oldName.ToString()).ToLower();
            string newName = DateTimeUtil.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + extName;
            return newName;
        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="image"></param>
        /// <param name="path"></param>
        /// <param name="filename"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns>图片路径</returns>
        public static string SaveImage(Image image, string path, string filename, int? width, int? height)
        {
            Dictionary<string, string> contentTypDict = GetImgFormat();
            string extName = Path.GetExtension(filename.ToString()).ToLower();

            //没有合适的格式
            if (!contentTypDict.ContainsKey(extName))
            {
                throw new Exception(BaseService.IMAGEFORMAT);
            }
            //获取当前目录
            string currentDirectory = Directory.GetCurrentDirectory();
            //生成新文件名
            string newFileName = CreateFileName(filename.ToString());
            //生成文件夹
            string fileFolder = DateTimeUtil.Now.ToString("yyyyMM");
            string filePath = Path.Combine(currentDirectory, "wwwroot", path, fileFolder);
            //创建文件夹
            if (!Directory.Exists(filePath))
                //创建pic文件夹
                Directory.CreateDirectory(filePath);
            //如果没有自定义大小
            if (width == null || height == null)
            {
                width = image.Width;
                height = image.Height;
            }
            int MaxWidth = 1980;
            int MaxHeight = 1080;
            //如果宽度超出
            if (width > MaxWidth)
            {
                height = height * MaxWidth / width;
                width = MaxWidth;
            }
            //如果长度超出
            if (height > MaxHeight)
            {
                width = width * MaxHeight / height;
                height = MaxHeight;
            }
            //新建一个bmp图片
            Bitmap bitmap = new Bitmap((int)width, (int)height);
            //新建一个画板
            Graphics g = Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(image, new Rectangle(0, 0, (int)width, (int)height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
            string fullName = Path.Combine(filePath, newFileName);
            try
            {
                switch (extName.ToLower())
                {
                    case ".gif":
                        bitmap.Save(fullName, ImageFormat.Gif);
                        break;
                    case ".jpg":
                        bitmap.Save(fullName, ImageFormat.Jpeg);
                        break;
                    case ".bmp":
                        bitmap.Save(fullName, ImageFormat.Bmp);
                        break;
                    case ".png":
                        bitmap.Save(fullName, ImageFormat.Png);
                        break;
                    default:
                        bitmap.Save(fullName, ImageFormat.Jpeg);
                        break;
                }

                return $"/{path}/{fileFolder}/{newFileName}";
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                image.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        public static string SaveFile(IFormFile file, string fileName, string path)
        {
            try
            {
                //获取当前目录
                string currentDirectory = Directory.GetCurrentDirectory();
                //生成新文件名
                string newFileName = CreateFileName(fileName.ToString());
                //生成文件夹
                string fileFolder = DateTimeUtil.Now.ToString("yyyyMM");
                string filePath = Path.Combine(currentDirectory, "wwwroot", path, fileFolder);
                using (FileStream fs = System.IO.File.Create(Path.Combine(filePath, newFileName)))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                return $"/{path}/{fileFolder}/{newFileName}";
            }
            catch (Exception)
            {
                throw;
            }

        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="name"></param>
        public static void DelHeadImage(string name)
        {
            try
            {
                //获取相对路径，处理成生成绝对路径
                name = name.Replace(BaseService.BaseUrl, "").Replace('/', Path.DirectorySeparatorChar);
                //
                //获取当前目录
                string currentDirectory = Directory.GetCurrentDirectory();
                //组装文件路径，删除文件
                string filePath = Path.Combine(currentDirectory, "wwwroot", name);
                if (System.IO.File.Exists(filePath))
                    System.IO.File.Delete(filePath);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
